package com.swak.config.setting;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import com.google.common.io.Files;
import com.swak.utils.Maps;
import com.swak.utils.StringUtils;

/**
 * 运行时的配置，默认不会创建，用户也不会感知，
 * 适合应对多用户自定义的场景；
 * 
 * @author 618lf
 */
class Runtime {

	private final File $store;
	private Properties $config = new Properties();
	private Map<String, String> config = Maps.newHashMap();
	private AtomicBoolean md = new AtomicBoolean(false);
	final String name;

	Runtime(String name) {
		this.name = StringUtils.endsWith(name, ".rt") ? name : name + ".rt";
		this.$store = new File(Settings.me().getRuntimeFile(), this.name);
		this.handleConfig();
	}

	void handleConfig() {
		try {
			$config.load(Files.asCharSource(this.$store, StandardCharsets.UTF_8).openStream());
			$config.keySet().forEach(key -> {
				config.put(String.valueOf(key), String.valueOf($config.get(key)));
			});
		} catch (Exception e) {
			$config = new Properties();
		}
	}

	/**
	 * 存储配置
	 */
	void storeConfig() {
		if (!md.get()) {
			return;
		}
		try {
			config.keySet().forEach(key -> {
				$config.put(key, config.get(key));
			});
			$config.store(Files.newWriter(this.$store, StandardCharsets.UTF_8), this.name);
		} catch (Exception e) {
		}
	}

	void putConfig(String key, String value) {
		this.md.compareAndExchange(false, true);
		this.config.put(key, value);
	}

	String getConfig(String key) {
		String value = config.get(key);
		return value == null ? StringUtils.EMPTY : value;
	}
}